package com.parsifal.bluetoothdemo.ui;

import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.parsifal.bluetoothdemo.R;

import java.util.ArrayList;

/**
 * Created by yangming on 17-4-1.
 */
public class ClientAdapter extends BaseAdapter {

    private LayoutInflater mInflater = null;

    private ArrayList<String> mMsgs = null;

    private static final String CLIENT = "Client : ";

    private static final String SERVER = "Server : ";

    private Context mContext = null;

    public ClientAdapter(Context context) {
        mContext = context;
        mInflater = LayoutInflater.from(context);
        mMsgs = new ArrayList<>();
    }

    public void clear() {
        mMsgs.clear();
        notifyDataSetChanged();
    }

    public void addClientMessage(String msg) {
        mMsgs.add(CLIENT + msg);
        notifyDataSetChanged();
    }

    public void addServerMessage(String msg) {
        mMsgs.add(SERVER + msg);
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return mMsgs.size();
    }

    @Override
    public Object getItem(int position) {
        return mMsgs.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.item_client, null);
        }
        TextView txMsg = ClientAdapter.ViewHolder.get(convertView, R.id.tx_msg);
        String msg = mMsgs.get(position);
        txMsg.setText(msg);
        if (msg.startsWith(CLIENT)) {
            txMsg.setTextColor(ContextCompat.getColor(mContext, R.color.colorDarkCyan));
        } else {
            txMsg.setTextColor(ContextCompat.getColor(mContext, R.color.colorFuchsia));
        }
        return convertView;
    }

    private static class ViewHolder {
        static <T extends View> T get(View view, int id) {
            SparseArray<View> viewHolder = (SparseArray<View>) view.getTag();
            if (viewHolder == null) {
                viewHolder = new SparseArray<>();
                view.setTag(viewHolder);
            }
            View childView = viewHolder.get(id);
            if (childView == null) {
                childView = view.findViewById(id);
                viewHolder.put(id, childView);
            }
            return (T) childView;
        }
    }
}
